/**
 * 校验是否为空对象
 * @param {object} obj 传入的用于校验的对象
 */
export function isEmptyObject(obj: object) {
  if (obj && Object.prototype.toString.call(obj) === "[object Object]") {
    if (Object.getOwnPropertyNames(obj).length > 0) {
      return false;
    } else {
      return true;
    }
  } else {
    return true;
  }
}

/**
 * 非空数组判断
 * @param {Array} arr 传入的用于校验的数组
 */
export function isEmptyArray(arr: Array<any>) {
  return arr && Array.isArray(arr) && arr.length > 0;
}

interface ICheckOptions {
  key: string;
  require?: boolean;
  validator?: (
    options: any,
    value: any,
    callback: (error: any) => void
  ) => void;
}
export function checkOptions(options: any, rules: Array<ICheckOptions>) {
  // 预定义自定义校验回调
  const callback = (error: any): void => {
    if (error) {
      throw error;
    }
  };

  if (arguments.length == 2) {
    if (!isEmptyObject(options)) {
      rules.forEach((rule, index) => {
        if (rule.require) {
          // 必填项
          if (
            options[rule.key] !== "" &&
            options[rule.key] !== undefined &&
            Object.prototype.hasOwnProperty.call(options, rule.key)
          ) {
            if (rule.validator) {
              rule.validator(options, options[rule.key], callback);
            }
          } else {
            throw new Error(`${rule.key}属性 is required`);
          }
        } else {
          // 非必填项
          if (rule.validator) {
            rule.validator(options, options[rule.key], callback);
          }
        }
      });
    }
  } else {
    throw new Error("未按指定规则传入校验数据");
  }
  return options;
}
